<template>
  <div>
    <el-row :gutter="10" class="full-height-row">
      <el-col :span="6" class="full-height-col">
        <el-card shadow="hover" class="full-height-card">
          <div>
            <el-tree
              ref="tree"
              :data="treeData"
              :props="defaultProps"
              node-key="id"
              show-checkbox
              default-expand-all
              @node-click="hangleNodeClick"
            />
          </div>
        </el-card>
      </el-col>
      <el-col v-if="subprojectId" :span="18" class="full-height-col">
        <el-card shadow="hover" class="full-height-card">
          <el-row>
            <el-col :span="15">
              <div style="display: flex;gap: 1em">
                <el-upload
                  ref="upload"
                  class="imp-button"
                  :action="aaa"
                  :on-change="importProject"
                  name="excelFile"
                  multiple
                  :show-file-list="false"
                  :auto-upload="false"
                >
                  <el-button type="warning">导入</el-button>
                </el-upload>
                <el-button v-if="roleName!=='总工'" type="primary" @click="save">保存</el-button>
                <el-button type="info" style="margin-left: 0" @click="cancel">取消</el-button>
              </div>
            </el-col>
            <el-col :span="9">
              <div class="right">
                <el-input
                  v-model="searchQuery"
                  placeholder="请输入搜索内容"
                  style="width: 20em; margin-right: 1em"
                  @keyup.enter.native="handleSearch"
                />
                <el-button type="primary" @click="handleSearch">搜索</el-button>
              </div>
            </el-col>
          </el-row>
          <div class="draggable" style="padding: 20px">
            <el-table
              :data="filteredPlans"
              border
              row-key="id"
            >
              <el-table-column align="center" label="工程部位" prop="inspectPart" min-width="10%" />
              <el-table-column align="center" label="序号" prop="id" min-width="10%">
                <template v-slot="scope">
                  <el-input
                    v-model="scope.row.floorIndex"
                    placeholder="请输入序号"
                    @focus="inputOnFocus(scope.row.floorIndex)"
                    @change="inputOnChange(scope.row)"
                  />
                </template>
              </el-table-column>
              <el-table-column align="center" label="检查内容" prop="items">
                <template v-slot="scope">
                  <div v-for="(item,index) in scope.row.items" :key="index">
                    <el-col style="width: 10%;height: 100%;display: flex; align-items: center; ">
                      <el-tag>{{ item.inspectType }}</el-tag>
                    </el-col>
                    <el-col style="width: 30%">
                      <span>分发间隔 </span>
                      <el-input
                        v-model="item.startDuration"
                        style="width: 70%"
                        type="number"
                        placeholder="请输入分发间隔"
                        :disabled="roleName==='总工'"
                      />
                    </el-col>
                    <el-col style="width: 30%">
                      <span>预警间隔 </span>
                      <el-input
                        v-model="item.alertDuration"
                        style="width: 70%"
                        type="number"
                        placeholder="请输入预警间隔"
                        :disabled="roleName==='总工'"
                      />
                    </el-col>
                    <el-col style="width: 30%">
                      <span>结束间隔 </span>
                      <el-input
                        v-model="item.finishDuration"
                        style="width: 70%"
                        type="number"
                        placeholder="请输入结束间隔"
                        :disabled="roleName==='总工'"
                      />
                    </el-col>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-card>
      </el-col>
    </el-row>

  </div>
</template>

<script>
import Sortable from 'sortablejs'
import { excelToJSON, getAllSubprojectsById, getProjectsById } from '@/api/project'
import router from '@/router'
import { getInspectPlan, importInspectPlan, postInspectPlan } from '@/api/schedule'
import { getUserById } from '@/api/authority'
import { getUserId } from '@/utils/storage'

export default {
  data() {
    return {
      aaa: '',
      roleName: '', // 当前用户的职位 总工只能看不能编辑，管理员可以编辑
      searchQuery: '', // 搜索框的内容
      plans: [],
      filteredPlans: [],
      subprojectId: null,
      treeData: [
        {
          id: 0,
          subprojectName: '郑州中原保利心语项目',
          disabled: true, // 不可勾选 根节点不能删除
          children: []
        }
      ],
      defaultProps: {
        children: 'children',
        label: 'subprojectName'
      },
      idCounter: 1,
      draggedRow: null, // 被拖动的行
      inputOldValue: ''// 输入框的旧值
    }
  },
  computed: {
    projectId() {
      return this.$route.query.projectId
    }
  },
  watch: {
    subprojectId(newVal) {
      if (newVal) {
        this.getInspectPlan()
      }
    }
    // plans: {
    //   handler(newValue) {
    //     // console.log('plans', newValue)
    //     this.isShowSave = true
    //   },
    //   deep: true
    // }
  },
  async  created() {
    await this.getProjectsById()
    await this.getAllSubprojectsById()
    await this.getRoleById()
    this.idCounter = this.treeData[0].children.length
  },
  mounted() {
    this.$nextTick(() => {

    })
  },
  methods: {
    async getProjectsById() {
      try {
        const { result } = await getProjectsById(this.projectId)
        this.treeData[0].subprojectName = result.projectName
        this.isCreated = result.isCreated
        this.notImport = !result.isCreated
        console.log('getProjectsById', result)
      } catch (error) {
        console.log(error)
      }
    },
    async getAllSubprojectsById() {
      try {
        const { result } = await getAllSubprojectsById(this.projectId)
        console.log('getAllSubprojectsById', this.projectId, result)
        this.treeData[0].children = result
      } catch (error) {
        console.log(error)
      }
    },
    async getInspectPlan() {
      try {
        const { result } = await getInspectPlan(this.projectId, this.subprojectId)
        console.log('获取检验批计划', result)
        this.plans = result.plans
        this.filteredPlans = result.plans

        // for (let i = 0; i < this.plans.length; i++) {
        //   // this.$set(this.plans[i], 'id', i)
        //   this.$set(this.plans[i], 'floorIndex', i + 1)
        //   // this.$set(this.filteredPlans[i], 'id', i)
        //   this.$set(this.filteredPlans[i], 'floorIndex', i + 1)
        // }

        // 拖拽功能
        // this.rowDrop()
      } catch (error) {
        console.log(error)
      }
    },
    async postInspectPlan(data) {
      try {
        const { result } = await postInspectPlan(data)
        console.log('更新检验批计划', result)
        this.$message.success('更新成功')
        // 把分项目检验批计划页面变空
        this.subprojectId = null
        this.searchQuery = ''
      } catch (error) {
        console.log(error)
      }
    },
    async excelToJSON(data) {
      try {
        const { result } = await excelToJSON(data)
        console.log('上传Excel表格返回所有内容转成的JSON', result)
        result.forEach(item => {
          const temp = { inspectPart: item['工程部位'], items: [] }
          if (item['钢筋原材预计分发日期'] !== '') {
            temp.items.push({
              inspectType: '钢筋原材',
              approStartDate: item['钢筋原材预计分发日期'],
              alertDate: item['钢筋原材预警日期'],
              approFinishDate: item['钢筋原材预计结束日期']
            })
          }
          if (item['钢筋加工预计分发日期'] !== '') {
            temp.items.push({ inspectType: '钢筋加工',
              approStartDate: item['钢筋加工预计分发日期'],
              alertDate: item['钢筋加工预警日期'],
              approFinishDate: item['钢筋加工预计结束日期']
            })
          }
          if (item['钢筋连接预计分发日期'] !== '') {
            temp.items.push({
              inspectType: '钢筋连接',
              approStartDate: item['钢筋连接预计分发日期'],
              alertDate: item['钢筋连接预警日期'],
              approFinishDate: item['钢筋连接预计结束日期']
            })
          }
          if (item['钢筋安装预计分发日期'] !== '') {
            temp.items.push({
              inspectType: '钢筋安装',
              approStartDate: item['钢筋安装预计分发日期'],
              alertDate: item['钢筋安装预警日期'],
              approFinishDate: item['钢筋安装预计结束日期']
            })
          }
          if (item['模板安装预计分发日期'] !== '') {
            temp.items.push({
              inspectType: '模板安装',
              approStartDate: item['模板安装预计分发日期'],
              alertDate: item['模板安装预警日期'],
              approFinishDate: item['模板安装预计结束日期']
            })
          }
          if (item['混凝土施工预计分发日期'] !== '') {
            temp.items.push({
              inspectType: '混凝土拌合物',
              approStartDate: item['混凝土拌合物预计分发日期'],
              alertDate: item['混凝土拌合物预警日期'],
              approFinishDate: item['混凝土拌合物预计结束日期']
            })
          }
          if (item['混凝土施工预计分发日期'] !== '') {
            temp.items.push({
              inspectType: '混凝土施工',
              approStartDate: item['混凝土施工预计分发日期'],
              alertDate: item['混凝土施工预警日期'],
              approFinishDate: item['混凝土施工预计结束日期']
            })
          }
          if (item['现浇结构预计分发日期'] !== '') {
            temp.items.push({
              inspectType: '现浇结构',
              approStartDate: item['现浇结构预计分发日期'],
              alertDate: item['现浇结构预警日期'],
              approFinishDate: item['现浇结构预计结束日期']
            })
          }
          this.plans.push(JSON.parse(JSON.stringify(temp)))
        })
        console.log('plans', this.plans)
      } catch (error) {
        console.log(error)
      }
    },
    async importInspectPlan(data) {
      try {
        const { result } = await importInspectPlan(this.projectId, this.subprojectId, data)
        console.log('导入检验批计划', result)
        this.$message.success('导入成功')
        // 获取检验批计划,刷新页面
        await this.getInspectPlan()
        // this.rowDrop()
      } catch (error) {
        console.log(error)
      }
    },
    async getRoleById() {
      try {
        const { result } = await getUserById(getUserId())
        console.log('当前用户职位', result)
        this.roleName = result.roleName
        console.log(this.roleName)
      } catch (error) {
        console.log(error)
      }
    },
    handleSearch() {
      if (!this.searchQuery) {
        // 如果搜索框为空，显示所有数据
        this.filteredPlans = this.plans
        return
      }

      // 过滤数据，根据工程部位(inspectPart)进行搜索
      this.filteredPlans = this.plans.filter(plan =>
        plan.inspectPart && plan.inspectPart.includes(this.searchQuery)
      )
    },
    // 点击树的节点
    hangleNodeClick(node) {
      console.log('点击树的节点', node, this.idCounter)
      if (node.id === 0) return
      this.isShow = 2
      this.subprojectId = node.subprojectId
      this.notImport = !this.subprojectId
    },
    importProject(file) {
      const fd = new FormData()
      // console.log('file', file)
      fd.append('file', file.raw)
      this.importInspectPlan(fd)
      if (this.$refs.upload) {
        this.$refs.upload.clearFiles()// 清空上传文件
      }
    },
    // 在输入框获得焦点时记录旧值
    inputOnFocus(val) {
      console.log('val', val)
      this.oldValue = val
    },
    inputOnChange(row) {
      const val = row.floorIndex
      if (val <= 0) {
        this.$message.warning('请输入正数')
        row.floorIndex = this.oldValue
        return
      }
      if (val > this.plans.length) {
        this.$message.warning(`当前只有${this.plans.length}个检验批计划`)
        row.floorIndex = this.oldValue
        return
      }
      if (val === null || val === '') {
        this.$message.warning('请输入数字')
        row.floorIndex = this.oldValue
        return
      }
      console.log('inputOnChange', val)
      // 改变plans数组
      this.plans.sort((a, b) => {
        return a.floorIndex - b.floorIndex
      })
      this.handleSearch()
    },
    // 行拖拽
    rowDrop() {
      // 此时找到的元素是要拖拽元素的父容器
      const tbody = document.querySelector('.draggable .el-table__body-wrapper tbody')
      const _this = this
      Sortable.create(tbody, {
        //  指定父元素下可被拖拽的子元素
        draggable: '.draggable .el-table__row',
        onEnd({ newIndex, oldIndex }) {
          console.log('newIndex', newIndex, 'oldIndex', oldIndex)

          // 改变plans数组
          const newIdx = _this.plans.findIndex(item => item.id === _this.filteredPlans[newIndex].id)
          const oldIdx = _this.plans.findIndex(item => item.id === _this.filteredPlans[oldIndex].id)
          console.log('newIdx', newIdx, 'oldIdx', oldIdx)
          _this.updatePlan(oldIdx, newIdx)
        }
      })
    },
    save() {
      const data = {
        projectId: this.projectId,
        subprojectId: this.subprojectId,
        plans: this.plans
      }
      this.postInspectPlan(data)
    },
    cancel() {
      router.back()
    },
    // 改变plans数组
    updatePlan(oldIdx, newIdx) {
      const currRow = this.plans.splice(oldIdx, 1)[0]
      this.plans.splice(newIdx, 0, currRow)
      if (oldIdx >= newIdx) {
        [oldIdx, newIdx] = [newIdx, oldIdx]
      }
      for (let i = oldIdx; i <= newIdx; i++) {
        this.plans[i].floorIndex = i + 1
      }
      // 重新搜索
      this.handleSearch()
    }
  }
}
</script>

<style scoped>
.full-height-row {
  height: 100%;
}

.full-height-col {
  height: 100%;
}

.full-height-card {
  height: 100%;
  display: flex;
  flex-direction: column;
}

/* 让行可以拖拽 */
/*::v-deep .el-table__row {
  cursor: move; !* 鼠标变成拖拽样式 *!
  user-select: none; !* 防止选中文本干扰拖拽 *!
}*/

/* 拖拽时的样式 */
/*::v-deep .el-table__row.dragging {
  opacity: 0.5;
  background: #f5f7fa;
}*/
</style>
